import positioning
import core

import logging
logger = logging.getLogger(__name__)

def isnan(num):
    return num != num


class Gps(core.BaseLocationService):
    
    def __init__(self, delay):
        core.BaseLocationService.__init__(self)
        self.delay = delay
        self.position_handler = None
        positioning.set_requestors([{"type":"service", "format":"application", "data":"test_app"}]) 
            
    def callback(self, evt):
        pos = evt['position']
        p = pos['latitude'], pos['longitude']
        if isnan(p[0]) or isnan(p[1]):
            logger.debug('current location invalid')
            return
        if self.position_handler:
            self.position_handler.handle_position(p)
    
    def start_service(self):
        logger.debug("starting gps")
        ival = self.delay * 1000000
        positioning.position(callback=self.callback, interval=ival)
        
    def stop_service(self):
        logger.debug("stopping gps")
        positioning.stop_position()
        